(function($, im, doc) {
	var recordCancel = false;
	var recorder = null;
	var audio_tips = document.getElementById("audio_tips");
	var startTimestamp = null;
	var stopTimestamp = null;
	var stopTimer = null;
	var timeLen = 0;
	var MIN_SOUND_TIME = 500;
	var parseTime = function(len) {
		if(len < 1000) {
			return '1秒';
		}
		var s = Math.round(len / 1000);
		if(s < 60) {
			return s + '秒';
		} else {
			return Math.floor(s / 60) + '分' + (s % 60) + '秒';
		}
	};
	//录音语音文件转base64字符串
	var Audio2dataURL = function(path) {
		//console.log(path);
		im.sendMsg({
			type: 'sound',
			//content: path,
			content: plus.io.convertLocalFileSystemURL(path),
			extras: {
				timelen: parseTime(timeLen),
				len: timeLen
			}
		}, 1);
		im.playsendSound('fasong');
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			entry.file(function(file) {
				var reader = new plus.io.FileReader();
				reader.onloadend = function(e) {
					var base64 = e.target.result;
					//var str = e.target.result.split("base64,");
					//var base64 = str[1];
					/*
					if($.os.ios) {
						var base64 = e.target.result.replace('data:audio/vnd.wave;base64,', '');
						var ftype = 'wav';
					} else {
						var base64 = e.target.result.replace('data:audio/amr;base64,', '');
						var ftype = 'amr';
					}*/

					//console.log(base64);
					//console.log(apiurl + 'index/upload');
					//$.post(apiurl + 'index/upload', {
					$.post(upurl, {
						uid : im.uid,
						file: base64,
						//ftype : ftype,
						type: 'sound',
						path : path
					}, function(res) {
						//console.log(timeLen);
						//console.log(JSON.stringify(res));
						res = JSON.parse(res);
						console.log(res.status);
						if(res && res.url) {
							im.sendMsg({
								type: 'sound',
								content: res.url,
								extras: {
									timelen: parseTime(timeLen),
									len: timeLen
								}
							}, 2);
						} else {
							mui.toast("发送失败2！");
						}
					});

				};
				reader.readAsDataURL(file);
			}, function(e) {
				mui.toast("读写出现异常: " + e.message);
			})
		})
	}

	var boxMsgSoundHold = function(event) {
		recordCancel = false;
		if(stopTimer) clearTimeout(stopTimer);
		audio_tips.innerHTML = "手指上划，取消发送";
		im.boxSoundAlert.classList.remove('rprogress-sigh');
		setSoundAlertVisable(true);
		recorder = plus.audio.getRecorder();
		if(recorder == null) {
			plus.nativeUI.toast("不能获取录音对象");
			return;
		}
		var t = 0;
		var min = 2;
		ri = setInterval(function() {
			t++;
			audio_tips.innerHTML = "手指上划，取消发送";
			if(t > min * 60) {
				clearInterval(ri);
				ri = null;
				recorder.stop();
				im.boxSoundAlert.style.display = 'none';
				mui.toast("录音最大时间为 " + min + "分钟");
			}
		}, 1000);
		startTimestamp = (new Date()).getTime();
		recorder.record({
			filename: "_doc/audio/"
		}, function(path) {
			if(recordCancel) return;
			t = 0;
			clearInterval(ri);
			ri = null;
			Audio2dataURL(path);

		}, function(e) {
			clearInterval(ri);
			ri = null;
			t = 0;
			plus.nativeUI.toast("录音时出现异常");
		});
	};

	var setSoundAlertVisable = function(show) {
		if(show) {
			im.boxSoundAlert.style.display = 'block';
			im.boxSoundAlert.style.opacity = 1;
		} else {
			im.boxSoundAlert.style.opacity = 0;
			//fadeOut 完成再真正隐藏
			setTimeout(function() {
				im.boxSoundAlert.style.display = 'none';
			}, 200);
		}
	};

	var boxMsgSoundDrag = function(event) {
		//console.log('drag');
		if(Math.abs(event.detail.deltaY) > 50) {
			if(!recordCancel) {
				recordCancel = true;
				if(!audio_tips.classList.contains("cancel")) {
					audio_tips.classList.add("cancel");
				}
				audio_tips.innerHTML = "松开手指，取消发送";
			}
		} else {
			if(recordCancel) {
				recordCancel = false;
				if(audio_tips.classList.contains("cancel")) {
					audio_tips.classList.remove("cancel");
				}
				audio_tips.innerHTML = "手指上划，取消发送";
			}
		}
	};
	var boxMsgSoundRelease = function(event) {
		//console.log('release');
		if(audio_tips.classList.contains("cancel")) {
			audio_tips.classList.remove("cancel");
			audio_tips.innerHTML = "手指上划，取消发送";
		}
		//
		stopTimestamp = (new Date()).getTime();
		timeLen = stopTimestamp - startTimestamp;
		if(timeLen < MIN_SOUND_TIME) {
			audio_tips.innerHTML = "录音时间太短";
			im.boxSoundAlert.classList.add('rprogress-sigh');
			recordCancel = true;
			stopTimer = setTimeout(function() {
				setSoundAlertVisable(false);
			}, 500);
		} else {
			setSoundAlertVisable(false);
		}
		recorder && recorder.stop();
	};
	var footerRightRelease = function(event) {
		var soundbtn = doc.querySelector('#msg-image');
		if(soundbtn.classList.contains('fa-wpexplorer')) {
			soundbtn.classList.add('fa-keyboard-o');
			soundbtn.classList.remove('fa-wpexplorer');
			im.boxMsgText.style.display = 'none';
			im.boxMsgSound.style.display = 'block';
			//doc.querySelector('#msg-type').style.display = 'none';
			//doc.querySelector('#msg-more').style.display = 'block';
			//doc.querySelector('#biaoqing').classList.add('icon-biaoqing');
			//doc.querySelector('#biaoqing').classList.remove('fa-keyboard-o');

			doc.body.focus();
			im.boxMsgText.blur();
		} else if(soundbtn.classList.contains('fa-keyboard-o')) {
			soundbtn.classList.add('fa-wpexplorer');
			soundbtn.classList.remove('fa-keyboard-o');
			im.boxMsgSound.style.display = 'none';
			im.boxMsgText.style.display = 'block';

		}
		doc.querySelector('#biaoqingbao').style.display = 'none';
			doc.querySelector('#Gallery').style.display = 'none';
			doc.querySelector('footer').style.bottom = '0px';
	};
	var player;
	var hs;
	//var onplay = 0;
	var playsound = function(el) {
		//player.volume = 1;
		//player.loop = false;
		/*
		if(onplay === 2) {
			var dur = player.getDuration();
			if(dur > 0) {
				player.seekTo(dur);
				//player.resume();
			}
		}*/
		//onplay = 1;
		
		//if($.os.android) {
			player.play(function(){
				audio_area.classList.remove('playing');
				player.src = '';
				progress_bar.style.width = '0%';
				clearInterval(hs);
			});
		/*}else{
			player.play();
		}*/
		
		//player.play();
		var audio_area = el.querySelector('.audio_area');
		
		var msgLen = el.getAttribute('data-len'); //总时长
		var progress_bar = el.querySelector(".progress_bar");

		var bu = 50;
		var seteval = Math.round(msgLen / bu); //执行的次数
		var num = (100 / seteval).toFixed(3); //每次增加的百分比
		var intnum = function(n) {
			return Math.round(n * 100) / 100;
		};
		//console.log(seteval);
		//console.log(msgLen);
		//console.log(num);
		if(hs) {
			clearInterval(hs);
		}

		var i = 0;
		var haslen = progress_bar.getAttribute('data-width') * 1;
		if(haslen >= 100) {
			progress_bar.setAttribute('data-width', 0);
			haslen = 0;
		}
		
		hs = setInterval(function() {
			i++;
			if(i > seteval || haslen > 100) {
				clearInterval(hs);
				progress_bar.style.width = '0%';
			} else {
				haslen = intnum(haslen + intnum(num));
				//console.log(haslen);
				progress_bar.setAttribute('data-width', haslen);
				progress_bar.style.width = haslen + '%';
			}

		}, bu);
		audio_area.classList.add('playing');
		/*
		if($.os.ios) {
			
			player.addEventListener('ended', function(e) {
				console.log(JSON.stringify(e));
				audio_area.classList.remove('playing');
				player.src = '';
				progress_bar.style.width = '0%';
				clearInterval(hs);
				//progress_bar.setAttribute('data-width', 0);
			}, false);
		}*/
		
	};
	var cachesound = function(loadUrl) {
		var urls = JSON.parse(localStorage.getItem('mysoundlist') || '{}');
		var rturl = urls[loadUrl];
		
		if(rturl) {
			return rturl;
		} else {
			//创建下载任务
			var dtask = plus.downloader.createDownload(loadUrl, {
				filename: '_doc/audio/'
			}, function(d, status) {
				if(status == 200) {
					//console.log(JSON.stringify(d));
					//下载成功
					urls[loadUrl] = plus.io.convertLocalFileSystemURL(d.filename);
					//console.log(d.filename);
					//urls[loadUrl] = d.filename;
					localStorage.setItem('mysoundlist', JSON.stringify(urls));
				}
			}).start();
			return loadUrl;
		}

	}
	var msgItemTap = function(event) {
		var msgContent = this.getAttribute('data-content');
		var audio_area = this.querySelector('.audio_area');
		var hasplaying = document.querySelector('.playing');
		var id = this.parentNode.getAttribute('msg-id');
		hasplaying && hasplaying.classList.remove('playing');
		var chatdata = chat.getOne(im.roomId, id);
		var extras = JSON.parse(chatdata['extras']);
		/*
		var player = document.createElement('audio');
		msgContent = cachesound(msgContent);
		console.log(msgContent);
		player.src = msgContent;
		player.volume = 1;
		player.loop = false;
		player.play();
		*/
		//console.log(extras);
		if(!extras['isread']) {
			var isread = this.querySelector('.isread');
			if(isread) {
				isread.remove();
			}
		}
		extras['isread'] = 1;
		chat.edit(im.roomId, id, 'extras', JSON.stringify(extras));
		//console.log(extras);
		//if(!player) {
			//player = document.createElement('audio');
		if(player) {
			player.pause();
		}
		//player = plus.audio.createPlayer(msgContent);
		//msgContent = cachesound(msgContent);
		//console.log(msgContent);
		//player = plus.audio.createPlayer(msgContent);
		
		if($.os.android) {
			player = plus.audio.createPlayer(msgContent);
		}else{
			msgContent = cachesound(msgContent);
			//console.log(msgContent);
			player = document.createElement('audio');
			//player = document.getElementById('_tosoundarea');
			player.src = msgContent;
			//player.src = '/var/mobile/Containers/Data/Application/7539BCC8-94F2-4B93-AD84-3F05F20EEEAD/Documents/Pandora/apps/HBuilder/doc/audio/1521372372.wav';
			console.log(JSON.stringify(player.src));
			//player.volume = 1;
			//player.play();
		}
	
		playsound(this);
	

	};
	//var player = document.querySelector('#_tosoundarea');
	var _playsound = function(el) {
		var audio_area = el.querySelector('.audio_area');
		/*
		var msgLen = el.getAttribute('data-len'); //总时长
		var progress_bar = el.querySelector(".progress_bar");
		var haslen = progress_bar.getAttribute('data-width');
		var bu = 50;
		var seteval = Math.round(msgLen / bu); //执行的次数
		var num = (100 / seteval).toFixed(3); //每次增加的百分比
		var hs;

		console.log(seteval);
		console.log(msgLen);
		console.log(num);*/
		player.volume = 1;
		player.loop = false;
		player.play();

		audio_area.classList.add('playing');
		/*
		hs = setInterval(function() {
			haslen++;
			if(haslen > seteval) {
				clearInterval(hs);
			}
			num = num + num;
			console.log(num);
			progress_bar.setAttribute('data-width', haslen);
			progress_bar.style.width = num + '%';
		}, seteval);
		*/
		player.addEventListener('ended', function() {
			audio_area.classList.remove('playing');
			player.src = '';
			//clearInterval(hs);
			//progress_bar.setAttribute('data-width', 0);
		}, false);
		/*
		player.addEventListener('play', function(e) {
			//console.log(JSON.stringify(e));
			
			
		}, false);*/
	}
	var _msgItemTap = function(event) {
		var msgContent = this.getAttribute('data-content');
		var audio_area = this.querySelector('.audio_area');
		var hasplaying = document.querySelector('.playing');
		/*var hasbar = document.querySelector('.progress_bar');
		
		if(hasbar) {
			[].forEach.call(hasbar, function(item, index) {
				console.log(item);
			});
		}
		hasbar.style.width = '0%';*/
		hasplaying && hasplaying.classList.remove('playing');
		if($.os.ios) {
			if(player.src != msgContent) {
				player.src = msgContent;
				playsound(this);
			} else {
				if(player.paused) {
					playsound(this);
				} else {
					player.pause();
					audio_area.classList.remove('playing');
				}
			}
		} else {
			player = plus.audio.createPlayer(msgContent);
			var len = player.getPosition();
			if(!len || len < 2) {
				player.play();
				audio_area.classList.add('playing');
			}
			//var player = player.getDuration(); //获取音频总长度number 
			setTimeout(function() { //延时获取，否则可能没有返回长度 
				var num = player.getDuration();
				setTimeout(function() {
					audio_area.classList.remove('playing');
				}, num * 1000);
			}, 50);

		}

	};
	$.plusReady(function() {
		im.boxMsgSound.addEventListener("touchstart", function(e) {
			//console.log("start....");
			e.preventDefault();
		});
		//显示按住说话框
		im.footerRight.addEventListener('release', footerRightRelease, false);
		im.boxMsgSound.addEventListener('hold', boxMsgSoundHold, false);
		im.body.addEventListener('drag', boxMsgSoundDrag, false);
		im.boxMsgSound.addEventListener('release', boxMsgSoundRelease, false);
		$('#msg-list').on('tap', '.sound-area', msgItemTap, false);
	});

}(mui, im, document));